<?php

namespace app\admin\controller;

use app\admin\model\Permission;
use think\Db;
use think\Exception;
use think\facade\Url;
use think\response\Json;
use think\exception\DbException;
use think\Controller;
use app\admin\model\Role as RoleModel;

class Role extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $list = RoleModel::order('id','desc')->paginate($this->request->get('limit', 30));
            $data = [
                'code' => 0,
                'msg' => '正在请求中...',
                'count' => $list->total(),
                'data' => $list->items()
            ];
            return Json::create($data);
        }
        return $this->fetch();
    }

    public function add()
    {
        if ($this->request->isAjax()){
            $data = $this->request->param();
            $result = $this->validate($data,'app\admin\validate\Role');
            if ($result !== true){
                $this->error($result);
            }
            try{
                RoleModel::create($data);
            }catch (DbException $exception){
                $this->error('添加失败',null,$exception->getMessage());
            }
            $this->success('添加成功',Url::build('index'));
        }
        return $this->fetch();
    }

    public function edit()
    {
        $id = $this->request->param('id');
        $role = RoleModel::getOrFail($id);
        if ($this->request->isAjax()){
            $data = $this->request->param();
            $result = $this->validate($data,'app\admin\validate\Role');
            if ($result !== true){
                $this->error($result);
            }
            try{
                $role->name = $data['name'];
                $role->description = $data['description'];
                $role->save();
            }catch (DbException $exception){
                $this->error('更新失败',null,$exception->getMessage());
            }
            $this->success('更新成功',Url::build('index'));
        }
        $this->assign('model',$role);
        return $this->fetch();
    }

    /**
     * 删除角色，软删除
     */
    public function del()
    {
        $id = $this->request->param('id');
        $role = RoleModel::findOrEmpty($id);
        if ($role->isEmpty()){
            $this->error('角色不存在');
        }
        Db::startTrans();
        try{
            Db::name('user_role')->where('role_id',$id)->delete();
            $role->delete();
            Db::commit();
        }catch (DbException $exception){
            Db::rollback();
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }

    /**
     * 分配权限
     * @return mixed
     * @throws DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function permission()
    {
        $id = $this->request->param('id');
        $role = RoleModel::with('permissions')->getOrFail($id);
        $permissions = Permission::order('sort','asc')->select();
        foreach ($permissions as $permission){
            if (isset($role->permissions) && !$role->permissions->isEmpty()){
                foreach ($role->permissions as $p){
                    if ($permission->id==$p->id){
                        $permission->own = true;
                    }
                }
            }
        }
        $permissions = get_tree($permissions->toArray());
        if ($this->request->isAjax()){
            $data = $this->request->param('permissions',[]);
            Db::startTrans();
            try{
                //清除角色的原有权限
                Db::name('role_permission')->where('role_id',$id)->delete();
                //添加角色权限
                foreach ($data as $v){
                    Db::name('role_permission')->insert([
                        'role_id' => $id,
                        'permission_id' => $v,
                    ]);
                }
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->error('更新失败',null,$exception->getMessage());
            }
            $this->success('更新成功',Url::build('index'));
        }
        $this->assign('permissions',$permissions);
        $this->assign('role',$role);
        return $this->fetch();
    }

}
